import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import { getLoginInfo, Accountlogin, getRefreshCode } from '@/services/LoginLayout';

import { getUserInfo, getThemeList, switchTheme, getDutyScope } from '@/services/BaseLayout';

import {
  getLevelZeroJson,
  getTheme,
  getUserID,
  setLevelFirst,
  setLevelFirstJson,
  setLevelSecond,
  setLevelSecondJson,
  setLevelZero,
  setLevelZeroJson,
} from '@/utils/authority';

export interface IndexModelState {
  loginInfo?: any;
  systemInfo?: any;
  permissions?: any;
  themeInfo?: any;
  userInfo?: Record<string, any>;
  openWelcomeLayout?: Record<string, any>;
  welcomeLayout?: Record<string, any>;
}

export interface IndexModelType {
  namespace: 'baseLogin';
  state: IndexModelState;
  effects: {
    getLoginInfo: Effect;
    AccountLogin: Effect;
    getUserInfo: Effect;
    getThemeList: Effect;
    getSwitchThemeList: Effect;
    switchTheme: Effect;
    getDutyScope: Effect;
    getRefreshCode: Effect;
  };
  reducers: {
    saveLoginInfo: Reducer<IndexModelState>;
    saveSystemInfo: Reducer<IndexModelState>;
    savePermissions: Reducer<IndexModelState>;
    saveThemeInfo: Reducer<IndexModelState>;
    updateUserInfo: Reducer<IndexModelState>;
    changeWelocmeLayout: Reducer<IndexModelState>;
    saveWelcomeLayout: Reducer<IndexModelState>;
  };
}

const IndexModel: IndexModelType = {
  namespace: 'baseLogin',

  state: {
    loginInfo: {},
    systemInfo: {},
    themeInfo: {},
    permissions: null,
    userInfo: {},
    openWelcomeLayout: {
      isDraggable: false,
      isResizable: false,
      monitorLayout: false, //监听是否调用了布局接口
      layoutLoading: false, //布局接口loading
    },
    welcomeLayout: {},
  },

  effects: {
    /**
     * 首页获取验证码以及系统名称Logo
     */
    *getLoginInfo({ payload, callback }, { call, put }): any {
      const response = yield call(getLoginInfo, payload);
      callback(response);
      yield put({
        type: 'saveLoginInfo',
        payload: {
          loginInfo: response,
        },
      });
    },

    // 刷新登录信息
    *getRefreshCode({ payload, callback }, { call, put }): any {
      const response = yield call(getRefreshCode, payload);
      callback(response);
      yield put({
        type: 'saveLoginInfo',
        payload: {
          loginInfo: response,
        },
      });
    },

    /**
     * 登陆方法
     */
    *AccountLogin({ payload, callback }, { call, put }): any {
      const response = yield call(Accountlogin, payload);
      callback(response);
      yield put({
        type: 'saveSystemInfo',
        payload: response?.obj,
      });
    },

    /**
     * 获取用户详情
     */
    *getUserInfo({ payload, callback }, { call, put }): any {
      const response = yield call(getUserInfo, payload);

      callback(response);
    },

    /*获取主题*/
    *getThemeList({ payload, callback }, { call, put }): any {
      const response = yield call(getThemeList);

      if (response && response?.msgFlag) {
        yield put({
          type: 'saveThemeInfo',
          payload: response?.obj,
        });
      }

      callback(response);
    },

    /*获取主题*/
    *getSwitchThemeList({ payload, callback }, { call, put }): any {
      const response = yield call(getThemeList);

      if (response && response?.msgFlag) {
        yield put({
          type: 'saveThemeInfo',
          payload: response?.obj,
        });
      }

      callback(response);
    },

    /*切换主题*/
    *switchTheme({ payload, callback }, { call, put }): any {
      const response = yield call(switchTheme, payload);
      callback(response);
    },

    /* 获取不同的0，1，2不同的岗位id,以及垂直部门id */
    *getDutyScope({ payload, callback }, { call, put }): any {
      let positionID = payload?.positionID;
      const levelZeroResponse = yield call(getDutyScope, {
        level: 0,
        positionID,
      });
      const levelFirstResponse = yield call(getDutyScope, {
        level: 1,
        positionID,
      });
      const levelSecondResponse = yield call(getDutyScope, {
        level: 2,
        positionID,
      });

      const loopPositionIds = (levelList: any[]) => {
        return levelList?.map((item) => {
          if (item?.children) {
            loopPositionIds(item?.children);
          }

          // if (item?.attributes?.category === 0) {
          if (item?.textType == '0') {
            return;
          } else {
            return item?.id;
          }
        });
      };

      /**
       * 处理当前岗位的职权范围
       * @param leveList 0:公司数据, 1:部门数据, 2岗位
       * @param level  0:公司及其子公司, 1:管辖部门及其当前部门, 2岗位
       * @returns
       */
      const loopPositionIDS = (leveList: any[], level: string) => {
        let ids: string[] = [];
        let loop = (dataList: any[]) => {
          dataList?.forEach((item: any) => {
            if (item?.children && item?.children?.length > 0) {
              loop(item?.children);
            }
            if (item?.textType == level && item?.rank != 2) {
              ids?.push(item?.id);
            }
          });
        };
        loop(leveList);
        if (ids?.length > 0) {
          return ids?.toString();
        } else {
          return '';
        }
      };

      let levelZero = loopPositionIDS(levelZeroResponse?.obj, '0');
      let levelFirst = loopPositionIDS(levelFirstResponse?.obj, '1');
      let levelSecond = loopPositionIDS(levelSecondResponse?.obj, '2');

      // let levelZero = loopPositionIds(levelZeroResponse?.obj);
      // let levelFirst = loopPositionIds(levelFirstResponse?.obj);
      // let levelSecond = loopPositionIds(levelSecondResponse?.obj);

      setLevelZero(levelZero); //级别为0的部门      getLevelZero()   //获取公司权限
      setLevelFirst(levelFirst); //级别为1的部门    getLevelFirst()  //获取部门权限
      setLevelSecond(levelSecond); //级别为2的部门  getLevelSecond() //获取岗位权限

      if (levelZeroResponse?.obj && JSON.stringify(levelZeroResponse?.obj) != '{}') {
        setLevelZeroJson(JSON.stringify(levelZeroResponse?.obj));
      }
      if (levelFirstResponse?.obj && JSON.stringify(levelFirstResponse?.obj) != '{}') {
        setLevelFirstJson(JSON.stringify(levelFirstResponse?.obj));
      }
      if (levelSecondResponse?.obj && JSON.stringify(levelSecondResponse?.obj) != '{}') {
        setLevelSecondJson(JSON.stringify(levelSecondResponse?.obj));
      }
    },
  },

  reducers: {
    saveLoginInfo(state, action) {
      return {
        ...state,
        loginInfo: action.payload?.loginInfo,
      };
    },

    /**
     * 开启关闭首页布局
     */
    changeWelocmeLayout(state, action) {
      return {
        ...state,
        openWelcomeLayout: action.payload?.openWelcomeLayout,
      };
    },

    /**
     * 保存布局数据
     */
    saveWelcomeLayout(state, action) {
      return {
        ...state,
        welcomeLayout: action.payload?.welcomeLayout,
      };
    },

    saveSystemInfo(state, action) {
      return {
        ...state,
        systemInfo: action.payload,
      };
    },

    /* 保存不同岗位的权限信息 */
    savePermissions(state, action) {
      return {
        ...state,
        permissions: action.payload,
      };
    },

    /* 保存主题 */
    saveThemeInfo(state, action) {
      let themeInfo: any = action?.payload?.find((item: any) => item?.id === getTheme());
      return {
        ...state,
        themeInfo,
      };
    },

    /* 更新用户信息 */
    updateUserInfo(state, action) {
      return {
        ...state,
        userInfo: action?.payload,
      };
    },
  },
};

export default IndexModel;
